<template>
	<view class="tinymce-box">
		<Editor api-key="ei8kc55y3pdzcx9xc2y2j4vxbasfylju7qk8h86ms8knsgk2" v-model="contentValue" :init="init" :disabled="disabled"></Editor>
		<!-- 图片空间 -->
		<dx-image-space v-model="showUpload" :limit="limit" @confirm="confirm"></dx-image-space>
	</view>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import Editor from '@tinymce/tinymce-vue';
import useElFormItem from '@/uni_modules/dx-admin/libs/useElFormItem';
const { emitTrigger } = useElFormItem();
const props = withDefaults(
	defineProps<{
		modelValue: any;
		height?: number;
		apiKey?: string;
		disabled?: boolean;
		limit?: number;
	}>(),
	{
		height: 350,
		disabled: false,
		limit: 9,
	}
);
const contentValue = ref();
const isUpdate = ref(false);
const showUpload = ref(false);
const currentEditor = ref<any>();
watch(
	() => props.modelValue,
	(newProps) => {
		if (!isUpdate.value) {
			contentValue.value = newProps || '';
		}
	},
	{
		immediate: true,
	}
);

// 绑定关系
const $emit = defineEmits(['update:modelValue']);
watch(contentValue, (newProps) => {
	isUpdate.value = true;
	$emit('update:modelValue', newProps);
	emitTrigger();
	isUpdate.value = false;
});
/**
 * 确认上传
 * @param urls
 */
function confirm(urls: string[]) {
	let imageHtml = '';
	for (let img of urls) {
		imageHtml += `<img src="${img}" />`;
	}
	currentEditor.value?.insertContent(imageHtml);
}
/**
 * 初始化配置
 * @type {Ref<{}>}
 */
const init = ref({
	language_url: '/admin/uni_modules/dx-admin/static/tinymce/langs/zh-Hans.js', //引入语言包文件
	language: 'zh-Hans', //语言类型
	plugins: [
		// 'image',
		'code',
		'searchreplace',
		'fullscreen',
		'insertdatetime',
		'media',
		'table',
		'autolink',
		'anchor',
		'autosave',
		'codesample',
		'directionality',
		'emoticons',
		'lists',
		'link',
		'nonbreaking',
		'pagebreak',
		'preview',
		'save',
		'visualblocks',
		'visualchars',
		'wordcount',
		'charmap',
	],
	toolbar: [
		'undo redo code bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote removeformat subscript superscript searchreplace codesample',
		'hr bullist numlist dxImage link charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen',
	],
	setup: function (editor:any) {
		editor.ui.registry.addButton('dxImage', {
			icon: 'image',
			tooltip: '插入图片',
			onAction: function () {
				showUpload.value = true;
				currentEditor.value = editor;
			},
		});
	},
	height: props.height,
	branding: false,
	menubar: true,
});
</script>

<style lang="scss" scoped></style>
